import { defineNuxtPlugin, useFetch } from "nuxt/app"
import { type CzCloudUrl } from "./type"
interface CzCloudOptions {
  method?: 'POST' | 'GET' | 'DELETE' | 'PUT',
  body?: Record<string, string>,
  headers?: Record<string, string>,
  query?: Record<string, string>,
  params?: Record<string, string>,
}

interface CzCloudResponse {
  code: 500 | 200,
  data: any,
  msg: string
}

export function syncCzUrlType() {
  fetch(`${process.env.NUXT_CHENGZHI_GETWAY}/builder-api/func/functions`).then(res => res.json()).then(res => {
    const typeArr: string[] = []
    const data = res.data || []
    for (const item of data) {
      typeArr.push(`'/${item.workspaceKey}/${item.moduleKey}/${item.requestName}'`)
    }
   
    if(typeArr.length === 0){
       typeArr.push('`/${string}/${string}/${string}`')
    }
    
    import("node:fs").then(async fs => {
      const path = await import("node:path")
      const urlType = `export type CzCloudUrl = ${typeArr.join(' | ')}`
      const codePath = path.resolve(__dirname, './type.ts')
      const oldUrlType = fs.readFileSync(codePath).toString()
      if(oldUrlType == urlType){
        return
      }
      fs.writeFileSync(codePath, urlType)
    })
  })
}

async function $api(name: CzCloudUrl, options?: CzCloudOptions) {
  if (!options) {
    options = {}
  }

  if(import.meta.dev){
    console.log(`${process.env.NUXT_CHENGZHI_GETWAY}/api${name}`)
  }
  let url = `${process.env.NUXT_PUBLIC_CHENGZHI_GETWAY}/api${name}`
  if(import.meta.client){
    url = `${useRuntimeConfig().public.chengzhiGetway}/api${name}`
  }
  // 判断是否为有效的url, 不一定http开头
  if(!url.startsWith('http')){
    return Promise.resolve({
      code: 500,
      data: null,
      msg: 'url无效'
    })
  }
  const { data } = await $fetch<CzCloudResponse>(url, {
    method: options.method || 'GET',
    body: options.body,
    headers: options.headers,
    query: options.query,
    params: options.params,
    parseResponse: (val)=>{
      try {
        return JSON.parse(val)
      } catch (error) {
        console.log(error)
        return val
      }
    },
    credentials: 'include',
  })

  return Promise.resolve(data)
}

export default defineNuxtPlugin({
  parallel: true,
  enforce: 'post',
  env: {
    islands: false,
  },
  async setup(nuxtApp) {
    return {
      provide: {
        fetchCloudApi: $api,
      }
    }
  },
  hooks: {
    'app:created': () => {
      if (import.meta.env && import.meta.server) {
        syncCzUrlType()
      }
    },
    'vue:setup': () => {

    }
  },
})
